package com.powernode.impl;

import com.powernode.constant.AuthConstants;
import com.powernode.factory.LoginStrategyFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description: 自己的认证流程
 * @Author: Tong Ziyu
 * @Date: 2024/10/22 16:06
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private LoginStrategyFactory loginStrategyFactory;

    /**
     * 设置认证逻辑
     *
     * @param username the username identifying the user whose data is required.
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 通过RequestContextHolder获取request对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        // 从请求头中获取登录类型
        // 两种类型,一种是用户端,一种是管理员端,两种类型要发不同的令牌
        String loginType = request.getHeader(AuthConstants.LOGIN_TYPE);

        // 不使用下面的方式,使用策略模式
        /*
        // 判断请求来自哪个系统,如果来自sysUserLogin 则说明是管理员
        if (AuthConstants.SYS_USER_LOGIN.equals(loginType)){
            // 管理员端认证
        }

        // 如果来自memberLogin 则说明是用户
        if (AuthConstants.MEMBER_LOGIN.equals(loginType)){
            // 用户端认证
        }*/
        // 首先判断一下登录类型是否有,如果没有,直接抛出异常
        if (!StringUtils.hasText(loginType)){
            throw new InternalAuthenticationServiceException("非法登录类型");
        }

        // 使用策略模式
        // 完全符合开闭原则,对修改关闭,对扩展开放,如果还有别的登录类型,直接添加实现类即可,不需要修改原来的代码
        return loginStrategyFactory.getInstance(loginType).realLogin(username);
    }
}
